import React, { useEffect, useState, useRef, useCallback } from 'react';
import { useLocation, useParams } from 'react-router-dom';
import { useMessage } from '@/components/messageApi';
import { request } from '@/api/request';
import { useTranslation } from 'react-i18next';
import useIsMobile from '@/hooks/isMoboile';
import CollectionHeader, { SortOption } from './components/Collection_CollectionHeader';
import AICollectionGrid from './components/Collection_AICollectionGrid';

/**
 * 图片生成收藏页面
 */
const Collection: React.FC = () => {
    const location = useLocation();
    const { username } = useParams<{ username?: string }>();
    const scrollContainerRef = useRef<HTMLDivElement>(null);
    const headerRef = useRef<HTMLDivElement>(null);
    const { t } = useTranslation();
    const message = useMessage();
    const isMobile = useIsMobile();

    // 本地排序状态管理
    const [sortBy, setSortBy] = useState<SortOption>('newest');
    const [headerHeight, setHeaderHeight] = useState(72); // 默认高度

    // 管理模式状态
    const [isManageMode, setIsManageMode] = useState(false);
    const [selectedImages, setSelectedImages] = useState<string[]>([]);
    const [refreshTrigger, setRefreshTrigger] = useState(0);

    // 排序变更处理函数
    const updateSortBy = (newSortBy: SortOption) => {
        // console.log(`排序方式从 ${sortBy} 变更为 ${newSortBy}`);
        setSortBy(newSortBy);
    };

    // 管理模式切换处理函数
    const handleManageModeChange = (newIsManageMode: boolean) => {
        setIsManageMode(newIsManageMode);
        // 退出管理模式时清空选择
        if (!newIsManageMode) {
            setSelectedImages([]);
        }
    };

    // 选中图片变更处理函数
    const handleSelectedImagesChange = (newSelectedImages: string[]) => {
        setSelectedImages(newSelectedImages);
    };

    // 删除选中图片处理函数
    const handleDeleteSelected = async () => {
        if (selectedImages.length === 0) {
            message.warning(t('collection.selectImages'));
            return;
        }

        try {
            const userDataStr = localStorage.getItem('userData');
            const userData = userDataStr ? JSON.parse(userDataStr) : null;

            if (!userData?.visitor_uuid) {
                message.error(t('collection.errors.userDataIncomplete'));
                return;
            }

            // console.log('删除图片请求:', { task_id: selectedImages });

            const res = await request.post('/api/ai-person-image/delete-images', {
                task_id: selectedImages
            });

            // console.log('删除图片响应:', res.data);

            if (res.data.success) {
                const deletedCount = res.data.data?.deleted_count || selectedImages.length;

                // 清空选择并退出管理模式
                setSelectedImages([]);
                setIsManageMode(false);

                // 触发AICollectionGrid刷新
                setRefreshTrigger(prev => prev + 1);

                // 显示成功消息
                message.success(t('collection.deleteSuccess', { count: deletedCount }));

                // console.log(`成功删除 ${deletedCount} 张图片`);
            } else {
                message.error(res.data.message || t('collection.errors.deleteFailed'));
            }
        } catch (error) {
            // console.error('删除图片失败:', error);
            message.error(t('collection.errors.deleteNetworkError'));
        }
    };

    const passedData = location.state as {
        avatar?: string;
        id?: string;
        username?: string;
        images?: string[];
        created_at?: string;
    } | null; // 获取从路由状态传递的数据

    // 获取AI角色ID - 优先使用id字段，如果没有则使用username作为备用
    const aiPersonId = passedData?.id || passedData?.username || '';

    // console.log('🔍 AI角色ID调试信息:', {
    //     passedData,
    //     hasPassedData: !!passedData,
    //     aiPersonId,
    //     currentSortBy: sortBy
    // });

    return (
        <div className="min-h-screen bg-[rgb(19,19,19)] lg:scrollbar-hide">
            {/* 头部：PC端固定定位，移动端sticky */}
            <div
                ref={headerRef}
                className="sticky top-0 z-10  lg:top-16 lg:z-20"
                style={{
                    left: !isMobile ? '14rem' : '0', // PC端避开sidebar宽度
                    right: '0',
                    width: '100%', // PC端减去sidebar宽度
                }}
            >
                <CollectionHeader
                    sortBy={sortBy}
                    onSortChange={updateSortBy}
                    userInfo={passedData && passedData.avatar && passedData.username ? {
                        avatar: passedData.avatar,
                        username: passedData.username
                    } : undefined}
                    isManageMode={isManageMode}
                    onManageModeChange={handleManageModeChange}
                    selectedCount={selectedImages.length}
                    onDeleteSelected={handleDeleteSelected}
                />
            </div>

            {/* 内容区域：PC端添加顶部边距以避免被固定header遮挡 */}
            <div className='w-full mt-6 px-4 sm:px-6 md:px-8 lg:w-[90%] lg:mx-auto lg:px-0 lg:mt-6'>
                <AICollectionGrid
                    ai_person_id={aiPersonId}
                    sortBy={sortBy}
                    isManageMode={isManageMode}
                    selectedImages={selectedImages}
                    onSelectedImagesChange={handleSelectedImagesChange}
                    key={refreshTrigger} // 强制重新渲染以刷新数据
                />
            </div>
        </div>
    );
};

export default Collection;
